package com.sm.tools;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.sm.R;
import com.sm.bo.Student;

public class StudentsAutoCompleteAdapter extends ArrayAdapter<Student>
		implements Filterable {

	// private final String MY_DEBUG_TAG = "StudentAdapter";
	private ArrayList<Student> students;
	private ArrayList<Student> studentsAll;
	private ArrayList<Student> suggestions;
	private int viewResourceId;

	@SuppressWarnings("unchecked")
	public StudentsAutoCompleteAdapter(Context context, int textViewResourceId,
			ArrayList<Student> students) {
		super(context, textViewResourceId, students);
		this.students = students;
		this.studentsAll = (ArrayList<Student>) students.clone();
		this.suggestions = new ArrayList<Student>();
		this.viewResourceId = textViewResourceId;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(viewResourceId, null);
		}
		Student Student = students.get(position);
		if (Student != null) {
			TextView StudentNameLabel = (TextView) v.findViewById(viewResourceId);
			if (StudentNameLabel != null) {
				// Log.i(MY_DEBUG_TAG,
				// "getView Student Name:"+Student.getName());
				StudentNameLabel.setText(Student.getName());
			}
		}
		return v;
	}

	@Override
	public Filter getFilter() {
		return nameFilter;
	}

	Filter nameFilter = new Filter() {
		public String convertResultToString(Object resultValue) {
			String str = ((Student) (resultValue)).getName();
			return str;
		}

		@SuppressLint("DefaultLocale")
		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			if (constraint != null) {
				suggestions.clear();
				for (Student Student : studentsAll) {
					if (Student.getName().toLowerCase()
							.startsWith(constraint.toString().toLowerCase())) {
						suggestions.add(Student);
					}
				}
				FilterResults filterResults = new FilterResults();
				filterResults.values = suggestions;
				filterResults.count = suggestions.size();
				return filterResults;
			} else {
				return new FilterResults();
			}
		}

		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results) {
			@SuppressWarnings("unchecked")
			ArrayList<Student> filteredList = (ArrayList<Student>) results.values;
			if (results != null && results.count > 0) {
				clear();
				for (Student c : filteredList) {
					add(c);
				}
				notifyDataSetChanged();
			}
		}
	};
}
